<?php
/* --------------------------------------------------------------
   dependent.inc.php 2022-10-24
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2022 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------*/

/** @var DatabaseModel $this */
/** @var int $t_success */

if ($this->columnExists('customers_memo', 'memo_title')) {

    $mergeTitleAndTextQuery = 'UPDATE `customers_memo` SET `memo_text`=CONCAT(`memo_title`, "\n", `memo_text`)';
    $t_success              &= $this->query($mergeTitleAndTextQuery, true);
    
    $removeTitleColumnQuery = 'ALTER TABLE `customers_memo` DROP `memo_title`;';
    $t_success              &= $this->query($removeTitleColumnQuery, true);
    
    $changeCreationDateDefaultValue = 'ALTER TABLE `customers_memo` CHANGE `memo_date` `memo_date` DATETIME NOT NULL DEFAULT "1000-01-01 00:00:00";';
    $t_success                      &= $this->query($changeCreationDateDefaultValue, true);
    
    $addLastModifiedColumn = 'ALTER TABLE `customers_memo` ADD `last_modified` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP AFTER `memo_date`;';
    $t_success             &= $this->query($addLastModifiedColumn, true);
}

$firstUpdateExecution = false;

if ($this->columnExists('customers', 'customers_is_favorite') === false) {
    
    $addIsFavoriteColumn = 'ALTER TABLE `customers` ADD `customers_is_favorite` int(1) NOT NULL DEFAULT "0" AFTER `account_type`;';
    $t_success             &= $this->query($addIsFavoriteColumn, true);
    
    $firstUpdateExecution = true;
}

if ($firstUpdateExecution) {
    
    foreach (['customers_basket', 'customers_wishlist'] as $table) {
    
        $increaseCharacterLimitQuery = sprintf('ALTER TABLE `%s` CHANGE `customers_basket_date_added` `customers_basket_date_added` VARCHAR(19) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;',
                                               $table);
        $t_success                   &= $this->query($increaseCharacterLimitQuery, true);
    
        $addTimeToEntryQuery = sprintf('UPDATE `%s` SET `customers_basket_date_added`=
                                                 CONCAT(SUBSTRING(`customers_basket_date_added`, 1, 4), "-", SUBSTRING(`customers_basket_date_added`, 5, 2), "-", SUBSTRING(`customers_basket_date_added`, 7, 2), " 00:00:00")',
                                       $table);
        $t_success           &= $this->query($increaseCharacterLimitQuery, true);
    
        $query = sprintf('ALTER TABLE `%s` CHANGE `customers_basket_date_added` `customers_basket_date_added` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;',
                         $table);
        $t_success &= $this->query($query, true);
    }
    
}

if ($this->columnExists('customers', 'customers_is_tradesperson') === false) {
    
    $addCustomerMerchantColumn = "ALTER TABLE `customers` ADD `customers_is_tradesperson` TINYINT NOT NULL DEFAULT '0' AFTER `customers_newsletter_mode`;";
    $t_success                 &= $this->query($addCustomerMerchantColumn, true);
}

if ($this->columnExists('customers', 'customers_company') === false && $this->columnExists('address_book', 'customer_b2b_status') === true) {
    
    $addCustomerCompanyColumn = "ALTER TABLE `customers` ADD `customers_company` varchar(64) NOT NULL DEFAULT '' AFTER `customers_lastname`;";
    $t_success               &= $this->query($addCustomerCompanyColumn, true);
    
    // Query overwrites every existing entry of the customers table and inserts company name from `address_book` table to the new column
    $updateCustomerCompanyColumnQuery = "
    REPLACE INTO `customers` (
        `customers_id`, `customers_cid`, `customers_vat_id`, `customers_vat_id_status`,
        `customers_warning`, `customers_status`, `customers_gender`, `customers_firstname`,
        `customers_lastname`, `customers_dob`, `customers_email_address`, `customers_default_address_id`,
        `customers_telephone`, `customers_fax`, `customers_password`, `customers_newsletter`,
        `customers_newsletter_mode`, `customers_is_tradesperson`, `member_flag`, `delete_user`,
        `account_type`, `customers_is_favorite`, `password_request_key`, `payment_unallowed`,
        `shipping_unallowed`, `refferers_id`, `customers_date_added`, `customers_last_modified`,
        `customers_company`
    )
    SELECT
        `c`.`customers_id`, `c`.`customers_cid`, `c`.`customers_vat_id`, `c`.`customers_vat_id_status`,
        `c`.`customers_warning`, `c`.`customers_status`, `c`.`customers_gender`, `c`.`customers_firstname`,
        `c`.`customers_lastname`, `c`.`customers_dob`, `c`.`customers_email_address`, `c`.`customers_default_address_id`,
        `c`.`customers_telephone`, `c`.`customers_fax`, `c`.`customers_password`, `c`.`customers_newsletter`, `c`.`customers_newsletter_mode`,
        `c`.`customers_is_tradesperson`, `c`.`member_flag`, `c`.`delete_user`, `c`.`account_type`, `ab`.`customer_b2b_status`,
        `c`.`password_request_key`, `c`.`payment_unallowed`, `c`.`shipping_unallowed`, `c`.`refferers_id`, `c`.`customers_date_added`,
        `c`.`customers_last_modified`,
        `ab`.`entry_company`
    FROM `address_book` AS `ab`
    INNER JOIN `customers` AS `c` ON `ab`.`address_book_id`=`c`.`customers_default_address_id`";
    $t_success               &= $this->query($updateCustomerCompanyColumnQuery, true);
    
    $removeB2bColumnQuery = 'ALTER TABLE `address_book` DROP `customer_b2b_status`;';
    $t_success            &= $this->query($removeB2bColumnQuery, true);
}

$controllerGroupId = $this->getAdminAccessGroupIdByIdentifier('ROUTE', '/api.php/v3/customers');
if($controllerGroupId === false){
    $pageGroupId = $this->getAdminAccessGroupIdByIdentifier('ROUTE', 'admin/api/options');
    
    $this->addAdminAccessGroupItem($pageGroupId, 'ROUTE', '/api.php/v3/customers');
}

$customersGroupId = $this->getAdminAccessGroupIdByIdentifier('PAGE', 'customers.php');
if($customersGroupId !== false){
    
    $newRoutes = [
        '/admin/api/customers/search',
        '/admin/api/customer-configurations',
        '/admin/api/customer-products',
        '/admin/api/customers-overview',
        '/admin/api/customer-profile',
        '/admin/api/create-customer',
        '/admin/api/delete-customer',
        '/admin/api/delete-guests',
        '/admin/api/update-customer',
        '/admin/api/customer',
        '/admin/api/change-customer-password',
        '/admin/api/change-customer-disallowed-payment-and-shipping-modules',
        '/admin/api/change-customers-group',
        '/admin/api/validate-email',
        '/admin/api/customer-register',
        '/admin/api/customer-user-configuration',
        '/admin/api/log-admin-activities',
        '/admin/api/customer-address/update-default'
    ];
    
    array_walk($newRoutes, fn(string $route) => $this->addAdminAccessGroupItem($customersGroupId, 'ROUTE', $route));
    
    $query = <<<SQL
    UPDATE admin_access_group_items SET `identifier` = '/admin/customers' WHERE `identifier`='customers.php' AND `admin_access_group_id`='$customersGroupId'
    SQL;
    
    $t_success &= $this->query($query, true);
}

include __DIR__ . '/customer_registration_date_migration.php';

include __DIR__ . '/correct_ot_modules.php';

// Removes the DISPLAY_VPE_PRODUCT_OPTIONS configuration
$check = $this->query('SELECT `value` FROM `gx_configurations` WHERE `key` = "gm_configuration/DISPLAY_VPE_PRODUCT_OPTIONS"',
                      true);
if ($check->num_rows > 0) {
    $query     = "DELETE FROM `gx_configurations` WHERE `key` = 'gm_configuration/DISPLAY_VPE_PRODUCT_OPTIONS';";
    $t_success &= $this->query($query, true);
}

// Deletes the VPE columns for additional options
if ($this->table_column_exists('products_attributes', 'products_vpe_id')) {
    $query     = 'ALTER TABLE `products_attributes` DROP COLUMN `products_vpe_id`;';
    $t_success &= $this->query($query, true);
}
// Deletes the VPE columns for additional options
if ($this->table_column_exists('products_attributes', 'gm_vpe_value')) {
    $query     = 'ALTER TABLE `products_attributes` DROP COLUMN `gm_vpe_value`;';
    $t_success &= $this->query($query, true);
}
// Deletes the EAN column for additional options
if ($this->table_column_exists('products_attributes', 'gm_ean')) {
    $query     = 'ALTER TABLE `products_attributes` DROP COLUMN `gm_ean`;';
    $t_success &= $this->query($query, true);
}
include_once __DIR__ . '/HTML_mail_signature.php';

// Removes the SHOW_PRINT configuration
$check = $this->query('SELECT `value` FROM `gx_configurations` WHERE `key` = "gm_configuration/SHOW_PRINT"',
                      true);
if ($check->num_rows > 0) {
    $query     = "DELETE FROM `gx_configurations` WHERE `key` = 'gm_configuration/SHOW_PRINT';";
    $t_success &= $this->query($query, true);
}